package com.example.hospital.patient.wx.api.utils;

import java.security.SecureRandom;
import java.util.regex.Pattern;
import static com.sun.org.apache.xalan.internal.xsltc.compiler.Constants.CHARACTERS;

public class RandomStringUtil {
    private static final String DIGITS = "0123456789";
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String REGEX = "^[a-zA-Z0-9]+$";

    public static String generateRandomString(int length, String prefix, boolean onlyDigits, boolean onlyLetters) {
        if (length < 1 || length > 64) {
            throw new IllegalArgumentException("Length must be between 1 and 64");
        }
        if (!Pattern.matches(REGEX, prefix)) {
            throw new IllegalArgumentException("Prefix must match the regular expression: " + REGEX);
        }

        SecureRandom secureRandom = new SecureRandom();
        StringBuilder randomString = new StringBuilder(prefix);
        for (int i = prefix.length(); i < length; i++) {
            if (onlyDigits) {
                randomString.append(DIGITS.charAt(secureRandom.nextInt(DIGITS.length())));
            } else if (onlyLetters) {
                randomString.append(LETTERS.charAt(secureRandom.nextInt(LETTERS.length())));
            } else {
                randomString.append(CHARACTERS.charAt(secureRandom.nextInt(CHARACTERS.length())));
            }
        }
        return randomString.toString();
    }
}

